
:-use_module(library(sockets)).

port(4321).

/* Servidor */

server :-
	current_host(Host),
	server(Host).

server(Host) :-
	port(Port),
	socket('AF_INET', Socket),
	socket_bind(Socket, 'AF_INET'(Host,Port)),
	socket_listen(Socket, 5),
	socket_accept(Socket, _Client, Stream),
	server_loop(Stream),
	socket_close(Socket),
	format('Exit server~n', []).

server_loop(Stream) :-
	repeat,
		read(Stream, ClientRequest),
		format('Server received: ~q~n', [ClientRequest]),
		server_input(ClientRequest, ServerReply),
		server_reply(ServerReply, Stream),
	ClientRequest == client_shutdown, !.

server_input(ClientRequest, ServerReply) :-
	ClientRequest = client(ClientHost), !,
	ServerReply = server(accept(ClientHost)).
server_input(ClientRequest, ServerReply) :-
	ClientRequest = echo(ClientTerm), !,
	ServerReply = reply(echo(ClientTerm)).
server_input(ClientRequest, ServerReply) :-
	ClientRequest = end_of_file, !,
	ServerReply = client_shutdown.
server_input(ClientRequest, ServerReply) :-
	ClientRequest = client_shutdown, !,
	ServerReply = thread_shutdown.
server_input(ClientRequest, ServerReply) :-
	ServerReply = unknown_request(ClientRequest),
	format('Unknown client request: ~w~n', [ClientRequest]).


server_reply(client_shutdown, _ServerOut) :- format('Server: end of file.~n'), !.
server_reply(ServerReply, ServerOut) :-
	format(ServerOut, '~q.~n', [ServerReply]),
	flush_output(ServerOut).

/* Cliente */

client  :-
	current_host(Host),
	client(Host).

client(Host) :-
	port(Port),
	socket('AF_INET', Socket),
	socket_connect(Socket, 'AF_INET'(Host,Port), Stream),
	client_loop(5, Stream),
	socket_close(Socket),
	format('Exit client~n', []).

client_loop(0, Stream) :- !, client_mesg(Stream, client_shutdown).
client_loop(I, Stream) :-
	N is I - 1,
	client_mesg(Stream, echo(I)),
	client_loop(N, Stream).

client_mesg(Stream, Mesg) :-
	format('Client snd msg: ~w.~n', [Mesg]),
	format(Stream, '~w.~n', [Mesg]),
	flush_output(Stream),
	read(Stream, StreamTerm),
	format('Client rcv msg: ~w~n', [StreamTerm]).

























